<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@include file="/view/jsp/resource.jsp"%>
<!DOCTYPE html>
<html>
<head>

<%@include file="/view/jsp/css.jsp"%>
<link
	href="${ctx }/res/css/plugins/dataTables/dataTables.bootstrap.min.css"
	rel="stylesheet" />
<link
	href="${ctx }/res/css/plugins/dataTables/jquery.dataTables.min.css"
	rel="stylesheet" />
<link
	href="${ctx }/res/css/plugins/ztree/zTreeStyle/zTreeStyle.css"
	rel="stylesheet" />
<link href="${ctx }/res/css/style.css?v=2.2.0" rel="stylesheet" />
<title>ash快速开发框架</title>
</head>
<body>
	<div id="wrapper">
		<%@include file="/view/jsp/menu.jsp"%>
		<div id="page-wrapper" class="yin-bg dashbard-1">
			<%@include file="/view/jsp/top.jsp"%>
			<!-- 面包屑导航开始 -->
			<div class="row wrapper border-bottom white-bg page-heading">
				<div class="col-lg-6">
					<h2>栏目列表</h2>
					<ol class="breadcrumb">
						<li><a href="${ctx }">主页</a></li>
						<li><a>权限管理</a></li>
						<li><strong>栏目列表</strong></li>
					</ol>
				</div>
				<div class="col-lg-6">
					<div class="btn-group headerbtn">
                                        <button class="btn btn-warning checkAll" type="button" class=""><i class='fa fa-check-square'></i>全选</button>
                                        <button class="btn btn-primary toggleCheck" type="button"><i class='fa fa-check-square-o'></i>反选</button>
                                        <button class="btn btn-info addBtn" type="button"><i class='fa fa-plus'></i>新增</button>
                                        <button class="btn btn-danger delBtn" type="button"><i class='fa fa-trash-o'></i>删除</button>
					</div>
				</div>
			</div>
			<div class="wrapper wrapper-content animated fadeIn ">
				  <div class="row editrow">
                    <div class="col-lg-8 col-lg-offset-2  ">
                        <div class="ibox box-shadow ">
                            <div class="ibox-title " >
                            <h2 style="width:90%;float:left" class="leader">新增类目</h2>
                                <div class="ibox-tools"  style="width:4%;float:right">
                                    <a class="collapse-link">
                                        <i class="fa fa-chevron-up"></i>
                                    </a>
                                    <a class="close-link">
		                                <i class="fa fa-times"></i>
		                            </a>
                                </div>
                            </div>
                            <div class="ibox-content ">
                                <form class="form-horizontal m-t validate" id="CategoryForm" action = "${ctx }/admin/security/category/save" method="POST">
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">名称：</label>
                                        <div class="col-sm-8">
                                        	 <input id="id" name="id" class="form-control" type="hidden">
                                             <input id="name" name="name" class="form-control required" type="text" >
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">代码：</label>
                                        <div class="col-sm-8">
                                            <input id="code" name="code" class="form-control required" type="text"  >
                                        </div>
                                    </div>
                                   
                                    <div class="form-group">
                                        <label class="col-sm-3 control-label">父类目：</label>
                                        <div class="col-sm-8">
                                           <input id="categoryPid" name="pid" type="hidden" >
                                           <input id="categroyPname" name="pName" class="form-control " type="text" >
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-sm-8 col-sm-offset-3">
                                            <button class="btn btn-primary" type="submit" >提 交</button>
                                            <button class="btn btn-primary resetAddForm" type="button">取 消</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
				<div class="row" style="height:40px;">
				</div>
			
				<div class="row">
					<div class="col-lg-12">
						<div class="ibox float-e-margins">
							<div class="ibox-content">
								<table
									class="table table-striped table-bordered table-hover categoryDataTable">
									<thead>
										<tr>
											<th></th>
											<th>序号</th>
											<th>名称</th>
											<th>别名</th>
											<th>上级序号</th>
											<th></th>
										</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
				
			</div>
		</div>
	</div>
	</div>
	<div id="categoryMenu" class="treemenu">
		<ul id="categoryTree" class="ztree " style="margin-top: 0;">
		</ul>
	</div>
	<%@include file="/view/jsp/js.jsp"%>
	<script src="${ctx}/res/js/json2.js"></script>
	<script src="${ctx}/res/js/plugins/dataTables/jquery.dataTables.min.js"></script>
	<script src="${ctx}/res/js/plugins/dataTables/dataTables.bootstrap.min.js"></script>
	<script src="${ctx}/res/js/plugins/validate/jquery.validate.min.js"></script>
	<script src="${ctx}/res/js/plugins/validate/messages_zh.min.js"></script>
	<script src="${ctx}/res/js/plugins/validate/validate_expand.js"></script>
	<script src="${ctx}/res/js/plugins/ztree/jquery.ztree.all-3.5.min.js"></script>
	<script type="text/javascript">
		var ash ={
			showEditRow: function(){
				var content = $('.editrow');
				content.slideDown(500);
			},
			_datatable:{},
			initEdit:function(){
				//编辑按钮
				$(".dataEdit").each(function(){
					$(this).on("click",function(){
						$.ajax({
				            url : _ctx + "/admin/security/category/"+$(this).attr("data"),
				            type : "get",
				            data : {},
				            dataType : "json",
				            success : function(returned) {
				            	if(returned.success){
				            		var data = returned.data;
					            	$("#CategoryForm input[name='id']").val(data.id);
					            	$("#CategoryForm input[name='name']").val(data.name);
					            	$("#CategoryForm input[name='code']").val(data.code);
					            	if(data.pid)
					            	$("#CategoryForm input[name='pid']").val(data.pid);
					            	if(data.parent&&data.parent.name)
					            	{
					            		$("#CategoryForm input[name='pName']").val((data.parent.name) ==null?"":data.parent.name );
					            	}
					            	ash.showEditRow();
				            	}
				            	else{
				            		layer.msg("数据获取失败.请联系系统管理员!");
				            	}
				            	
				            },
				            erorr : function(e) {
				            	layer.msg(e.message());	
				            }
				        });
					});	
				});	
			}
		};
		var curExpandNode=null;//临时存储打开的ztree 节点
		var ztree  ={
				settings:{ 
					async : {
					        enable : true,
					        contentType : "application/json",
					        url : _ctx + "/admin/security/category/tree.json?rodom="+Math.random()*1000,
			    	},
				    data : {
				        simpleData : {
				            enable : true,
				            idKey : "id",
				            pIdKey : "pid"
				        }
			    	},
			    	view : {
			        	dblClickExpand : false,
						showIcon: function(treeId, treeNode){
							return false;
						}
						
			    	},
			    	callback : {
			    		//单一节点展开
				        beforeExpand : function(treeId, treeNode){
				        	    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
				        	    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
				        	    var zTree = $.fn.zTree.getZTreeObj("categoryTree");
				        	    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
				        	        if (treeNode !== treeNodeP.children[i]) {
				        	            zTree.expandNode(treeNodeP.children[i], false);
				        	        }
				        	    }
				        	    while (pNode) {
				        	        if (pNode === treeNode) {
				        	            break;
				        	        }
				        	        pNode = pNode.getParentNode();
				        	    }
				        	    if (!pNode) {
				        	        if (treeNode === curExpandNode)
				        	            return;
				        	        if (curExpandNode && curExpandNode.open == true) {
				        	            var zTree = $.fn.zTree.getZTreeObj("categoryTree");
				        	            if (treeNode.parentTId === curExpandNode.parentTId) {
				        	                zTree.expandNode(curExpandNode, false);
				        	            } else {
				        	                var newParents = [];
				        	                while (treeNode) {
				        	                	treeNode = treeNode.getParentNode();
				        	                    if (treeNode === curExpandNode) {
				        	                        newParents = null;
				        	                        break;
				        	                    } else if (treeNode) {
				        	                        newParents.push(treeNode);
				        	                    }
				        	                }
				        	                if (newParents != null) {
				        	                    var oldNode = curExpandNode;
				        	                    var oldParents = [];
				        	                    while (oldNode) {
				        	                        oldNode = oldNode.getParentNode();
				        	                        if (oldNode) {
				        	                            oldParents.push(oldNode);
				        	                        }
				        	                    }
				        	                    if (newParents.length > 0) {
				        	                        zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
				        	                    } else {
				        	                        zTree.expandNode(oldParents[oldParents.length - 1], false);
				        	                    }
				        	                }
				        	            }
				        	        }
				        	        curExpandNode = treeNode;
				        	    }
				        },
				        onExpand : function(event, treeId, treeNode){
				        	curExpandNode = treeNode;
				        },
				        beforeClick : function(treeId, treeNode){
				        	
				        },
				        onClick : function(event,treeId, treeNode){
				        		/**  这是多选的代码
				        	 	var zTree = $.fn.zTree.getZTreeObj("categoryTree"), nodes = zTree.getSelectedNodes(), v = "", n = "";
				        	    nodes.sort(function compare(a, b) {
				        	        return a.id - b.id;
				        	    });
				        	    for (var i = 0, l = nodes.length; i < l; i++) {
				        	        v += nodes[i].id + ",";
				        	        n += nodes[i].name + ",";
				        	    }
				        	    if (v.length > 0)
				        	        v = v.substring(0, v.length - 1);
				        	    if (n.length > 0)
				        	        n = n.substring(0, n.length - 1);
				        	    **/
				        	    var obj = $("#categoryPid");//pid为隐藏的元素 存储获取的tree节点的id 方便提交给服务器
				        	    var objName = $("#categroyPname");
				        	    obj.attr("value", treeNode.id);
				        	    objName.attr("value", treeNode.name);
				        	    ztree.hide();
				        	    return false;
				        }
			    	}
			    },
			    show:function(){
			    	var obj = $("#categroyPname");//pName是触发tree的元素的id 使用时候请自行修改
			        var objset = $("#categroyPname").offset();
			        $("#categoryMenu").css({
			            left : objset.left + "px",
			            top : objset.top + obj.outerHeight() + "px",
			            width : obj.outerWidth() + "px"
			        }).slideDown("fast");
			        $("body").bind("mousedown", this.onBodyDown);
			    },
			    hide:function(){
			    	 $("#categoryMenu").fadeOut("fast");
			    	 $("body").unbind("mousedown", this.onBodyDown);
			    },
			    onBodyDown:function (event) {
			        if (!(event.target.id == "menuBtn" || event.target.id == "categoryMenu" || $(event.target).parents("#categoryMenu").length > 0)) {
			            ztree.hide();
			        }
			    }
		}
	
		$(function() {
			$.fn.zTree.init($("#categoryTree"), ztree.settings);
			$("#categroyPname").click(function(){
				ztree.show();
			});
			//加载数据
			ash._datatable = $(".categoryDataTable").dataTable(
							{
								language : {
									"sProcessing" : "处理中...",
									"sLengthMenu" : "显示 _MENU_ 项结果",
									"sZeroRecords" : "没有匹配结果",
									"sInfo" : "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
									"sInfoEmpty" : "显示第 0 至 0 项结果，共 0 项",
									"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
									"sInfoPostFix" : "",
									"sSearch" : "搜索:",
									"sUrl" : "",
									"sEmptyTable" : "表中数据为空",
									"sLoadingRecords" : "载入中...",
									"sInfoThousands" : ",",
									"oPaginate" : {
										"sFirst" : "首页",
										"sPrevious" : "上页",
										"sNext" : "下页",
										"sLast" : "末页"
									},
									"oAria" : {
										"sSortAscending" : ": 以升序排列此列",
										"sSortDescending" : ": 以降序排列此列"
									}
								},
								serverSide : true,
								"ajax" : _ctx + "/admin/security/category/data.json",
								"columns" : [
										{
											"data" : "id",
											"width" : "4%",
											"render" : function(data) {
												return "<input type='checkbox' class='selectable-checkbox' name='id' data='"+data+"'>";
											}
										},
										{
											"data" : "id",
											"width" : "4%"
										},
										{
											"data" : "name"
										},
										{
											"data" : "code"
										},
										{
											"data" : "pid"
										},
										{
											"data" : "id",
											"width" : "16%",
											"render" : function(data) {
												return "<a class='btn btn-xs btn-info dataEdit' data='"+data+"'><i class='fa fa-edit'></i>编辑</a> ";
											}
										}, ],
								deferRender : true
							});
			$('.categoryDataTable').on('draw.dt',function() {
				ash.initEdit();
			});
			
			//全选按钮
			$(".checkAll").on("click",function(){
				$("input:checkbox[name='id']").each(function(){
					$(this).prop("checked","checked");
				});
			});
			//反选按钮
			$(".toggleCheck").on("click",function(){
				$("input:checkbox[name='id']").each(function(){
					if($(this).prop("checked"))
						$(this).prop("checked",false);
					else
						$(this).prop("checked",true);
				});
			});
			//新增按钮
			$(".addBtn").on("click",function(){
				$("#CategoryForm")[0].reset();
				ash.showEditRow();
			});
			//删除按钮
			$(".delBtn").on("click",function(){
				 var checkedIds = "";
			        var _checked = $("input.selectable-checkbox:checked");
			        if(_checked.length==0)
			        {
			        	layer.msg("<H4><i class='fa fa-exclamation-circle'></i>警告!</H4><p>请勾选至少一条记录!</p>");
			        }
			        for (var i = 0; i < _checked.length; i++) {
			            checkedIds += $(_checked[i]).attr("data") + ",";
			        }
			        $.ajax({
			            url : _ctx + "/admin/security/category/delete",
			            type : "post",
			            data : {
			                id : checkedIds
			            },
			            dataType : "json",
			            success : function(returned) {
			            	layer.msg("<H4><i class='fa fa-check'></i></H4><p>删除成功!</p>");
			               	ash._datatable.fnDraw(); 
			               	$.fn.zTree.init($("#categoryTree"), ztree.settings);
			            },
			            erorr : function(e) {
			            	layer.msg(e.message());	
			            }
			        });
			});
			$(".resetAddForm").on("click",function(){
				$("#CategoryForm")[0].reset();
				$(".editRow").slideUp(500);
			})
			$(".validate").validate({
				submitHandler: function(form) {
					$.ajax({
						url:$(form).attr("action"),
						type:$(form).attr("method"),
						data:{
							id:$(".validate input[name='id']").val(),
							name:$(".validate input[name='name']").val(),
							code:$(".validate input[name='code']").val(),
							pid:$(".validate input[name='pid']").val()
						},
						datatype:"json",
						success:function(returned){
							if(returned.success)
							{
								layer.msg(returned.msg);
							}
							else
								layer.msg(returned.msg);
							$("#CategoryForm")[0].reset();
							$(".editRow").slideUp(500);
							ash._datatable.fnDraw(); 
							$.fn.zTree.init($("#categoryTree"), ztree.settings);
						},
						error:function(error){
							layer.msg(error);
						}
					})
				}
			});
		});
	</script>

</body>

</html>
